package com.easypoi.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.easypoi.handler.UserHandler;
import com.easypoi.entity.User;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @author 萧一旬
 * @date Create in 17:27 2020/9/17
 */
@RestController
public class ExcelPoiController {


    UserHandler userHandler = new UserHandler();

    /**
     * 导出
     *
     * @param response
     */
    @GetMapping("/exportExcel")
    public void exportExcel(HttpServletResponse response) {
        //这里可以自己的逻辑处理，传入条件连数据库做查询，最后得到一个list就行
        List<User> userList = userHandler.getUserList();
        System.out.println(userList.size());
        //title 和 sheetName可以设置为 null
        ExportParams params = new ExportParams("用户记录", "用户");
        Workbook workbook = ExcelExportUtil.exportExcel(params, User.class, userList);
        response.setHeader("Content-Disposition", "attachment;filename=" + System.currentTimeMillis() + ".xls");
        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setCharacterEncoding("UTF-8");
        try {
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 导入
     *
     * @param file
     * @throws Exception
     */
    @PostMapping("/importExcel")
    public void importExcel(MultipartFile file) throws Exception {
        ImportParams params = new ImportParams();
        params.setHeadRows(1);
        params.setTitleRows(1);
        long start = new Date().getTime();
        List<User> list = ExcelImportUtil.importExcel(
                file.getInputStream(),
                User.class, params);
        System.out.println(new Date().getTime() - start);
        list.forEach(user -> {
            System.out.println(user.toString());
        });
    }
}
